package com.yc.snacknet_vue.filter;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yc.snacknet_vue.utils.SessionKeys;

/**
 * 过滤后台 
 * company 源辰信息
 * @author 38929
 * @date 2020年8月13日
 * Email 1198865589@qq.com
 */
@WebFilter(filterName = "CheckFrontFilter", value = "/front/*")
public class CheckFrontFilter implements Filter{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//判断用户有没有登陆 -》 如果登陆了 我们将登陆的信息存储到session中
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		//判断是否登陆   即 session是否有值
		if(req.getSession().getAttribute(SessionKeys.CURRENTMEMLOGINACCOUNT)  == null ) {
			//未登录 跳转指定界面
			resp.setContentType("text/html;charset=utf-8");//防止页面乱码
			PrintWriter out = resp.getWriter();
			String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/";
			out.print("<script>alert('请先登陆。。。');location.href='" + basePath + "login.html';</script>");
			out.flush();//刷新缓冲区数据
			out.close();//会默认关闭流  可以省略
			return;
		}
		//获取用户请求的资源路径 /snacknet/front/cart.html
		String path = req.getRequestURI();
		
		//获取项目名   /snacknet
		String projectName = req.getContextPath(); 
		
		// /front/cart.html
		path = path.replace(projectName, "");
		//内部转发
		//req.getRequestDispatcher("../WEB-INF/" + path).forward(req, resp);
		req.getRequestDispatcher( path ).forward(req, resp);
	}
}
